package org.dousb.doupicture.domain.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dousb.doupicture.application.service.SpaceUserApplicationService;
import org.dousb.doupicture.application.service.UserApplicationService;
import org.dousb.doupicture.domain.user.entity.Space;
import org.dousb.doupicture.domain.user.entity.SpaceUser;
import org.dousb.doupicture.domain.user.entity.User;
import org.dousb.doupicture.domain.user.service.SpaceDomainService;
import org.dousb.doupicture.domain.user.valueobject.SpaceLevelEnum;
import org.dousb.doupicture.domain.user.valueobject.SpaceRoleEnum;
import org.dousb.doupicture.domain.user.valueobject.SpaceTypeEnum;
import org.dousb.doupicture.infrastructure.common.ErrorCode;
import org.dousb.doupicture.infrastructure.exception.BusinessException;
import org.dousb.doupicture.infrastructure.exception.ThrowUtils;
import org.dousb.doupicture.infrastructure.mapper.SpaceMapper;
import org.dousb.doupicture.interfaces.dto.space.SpaceAddRequest;
import org.dousb.doupicture.interfaces.dto.space.SpaceQueryRequest;
import org.dousb.doupicture.interfaces.vo.space.SpaceVO;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2025-10-09 08:18:42
 */
@Service
public class SpaceDomainServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceDomainService {

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    @Lazy
    private SpaceUserApplicationService spaceUserApplicationService;

//    @Resource
//    @Lazy
//    private DynamicShardingManager dynamicShardingManager;


    /**
     * 校验参数
     *
     * @param space
     * @param add
     */
    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);

        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(space.getSpaceType());

        //如果是新增
        if (add) {
            if (StrUtil.isBlank(spaceName)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            }
            if (spaceLevelEnum == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不能为空");
            }
            if (spaceTypeEnum == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型不能为空");
            }
        }
        //如果是修改
        if (spaceName != null && spaceLevelEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不存在");
        }
        if (StrUtil.isNotBlank(spaceName) && spaceName.length() > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称过长");
        }
        if (spaceTypeEnum == null && space.getSpaceType() != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型不存在");
        }
    }

    /**
     * 校验空间权限
     *
     * @param space
     * @param loginUser
     */
    @Override
    public void checkSpaceAuth(Space space, User loginUser) {
        //校验空间是否存在
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId()) && !loginUser.isAdmin()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作该空间");
        }
    }

    /**
     * 空间限额
     *
     * @param space
     */
    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (spaceLevelEnum != null) {
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
        }
    }

    /**
     * 新增空间
     *
     * @param spaceAddRequest
     * @return
     */
    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        //设置默认值
        if (StrUtil.isBlank(spaceAddRequest.getSpaceName())) {
            spaceAddRequest.setSpaceName("默认空间");
        }
        if (spaceAddRequest.getSpaceLevel() == null) {
            spaceAddRequest.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (spaceAddRequest.getSpaceType() == null) {
            spaceAddRequest.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        //填充数据
        this.fillSpaceBySpaceLevel(space);
        //校验参数
        this.validSpace(space, false);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        //权限校验
        if (SpaceLevelEnum.COMMON.getValue() != spaceAddRequest.getSpaceLevel() && !loginUser.isAdmin()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限创建其他空间级别");
        }
        //给用户加锁 确保每个用户仅能有一个空间
        //TODO 后续使用Redisson 分布式锁 确保每个用户仅能有一个空间
        String lock = String.valueOf(userId).intern();
        synchronized (lock) {
            Long newSpaceId = transactionTemplate.execute(status -> {
                boolean exists = this.lambdaQuery()
                        .eq(Space::getUserId, userId)
                        .eq(Space::getSpaceType, space.getSpaceType())
                        .exists();
                ThrowUtils.throwIf(exists, ErrorCode.PARAMS_ERROR, "每个用户每类空间类型仅能有一个");
                //写入数据库
                boolean result = this.save(space);
                ThrowUtils.throwIf(!result, ErrorCode.PARAMS_ERROR);
                //如果是团队空间 关联新增用户
                if (SpaceTypeEnum.TEAM.getValue() == space.getSpaceType()) {
                    //新增用户关联空间
                    SpaceUser spaceUser = new SpaceUser();
                    spaceUser.setSpaceId(space.getId());
                    spaceUser.setUserId(userId);
                    spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                    boolean save = spaceUserApplicationService.save(spaceUser);
                    ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "创建空间队员记录失败");
                }
                //创建分表
//                dynamicShardingManager.createSpacePictureTable(space);
                //返回新写入的id
                return space.getId();
            });
            //返回结果是包装类 可以做一些处理
            return Optional.ofNullable(newSpaceId).orElse(-1L);
        }
    }

    /**
     * 封装返回空间类
     *
     * @param space
     * @param request
     * @return SpaceVO
     */
    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        SpaceVO spaceVO = new SpaceVO();
        BeanUtils.copyProperties(space, spaceVO);
        return spaceVO;
    }

    /**
     * 获取空间列表
     *
     * @param spaceList
     * @return
     */
    @Override
    public List<SpaceVO> getSpaceVOList(List<Space> spaceList) {
        if (CollUtil.isEmpty(spaceList)) {
            return new ArrayList<>();
        }
        Set<Long> userIds = spaceList.stream()
                .map(Space::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Long, User> userMap = CollUtil.isEmpty(userIds)
                ? Collections.emptyMap()
                : userApplicationService.listByIds(userIds).stream()
                .collect(Collectors.toMap(User::getId, Function.identity()));

        return spaceList.stream()
                .map(space -> {
                    SpaceVO spaceVO = SpaceVO.objToVo(space);
                    Long userId = space.getUserId();
                    if (userId != null) {
                        User user = userMap.get(userId);
                        if (user != null) {
                            spaceVO.setUser(userApplicationService.getUserVO(user));
                        }
                    }
                    return spaceVO;
                })
                .collect(Collectors.toList());
    }

    /**
     * 封装查询条件
     *
     * @param spaceQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        if (spaceQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = spaceQueryRequest.getId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Long userId = spaceQueryRequest.getUserId();
        Integer spaceType = spaceQueryRequest.getSpaceType();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        QueryWrapper<Space> spaceQueryWrapper = new QueryWrapper<>();
        spaceQueryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        spaceQueryWrapper.eq(ObjUtil.isNotNull(spaceType), "spaceType", spaceType);
        spaceQueryWrapper.eq(ObjUtil.isNotNull(userId), "userId", userId);
        spaceQueryWrapper.eq(ObjUtil.isNotNull(spaceLevel), "spaceLevel", spaceLevel);
        spaceQueryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
        spaceQueryWrapper.orderBy(StrUtil.isNotBlank(sortField), "ascend".equals(sortOrder), sortField);
        return spaceQueryWrapper;
    }


}




